import { ref } from 'vue'
import { Levels } from './token'

const html = document.documentElement

/**
 * 解析颜色为 RGB 对象
 */
function parseColor(color) {
  if (color.startsWith('#')) {
    // HEX 格式
    const hex = color.slice(1)
    const bigint = Number.parseInt(hex, 16)
    return {
      r: (bigint >> 16) & 255,
      g: (bigint >> 8) & 255,
      b: bigint & 255,
      a: 1, // 默认不透明
    }
  }
  else if (color.startsWith('rgba')) {
    // RGBA 格式
    const [r, g, b, a] = color
      .match(/rgba?\(([^)]+)\)/)[1]
      .split(',')
      .map(v => Number.parseFloat(v))
    return { r, g, b, a: a || 1 }
  }
  else if (color.startsWith('hsl')) {
    // HSL 格式
    const [h, s, l] = color
      .match(/hsl\(([^)]+)\)/)[1]
      .split(',')
      .map(v => Number.parseFloat(v))
    return hslToRgb(h, s / 100, l / 100)
  }
  console.warn('不支持的颜色格式:', color)
  return null
}

/**
 * HSL 转 RGB
 */
function hslToRgb(h, s, l) {
  let r, g, b
  if (s === 0) {
    r = g = b = l // 灰色
  }
  else {
    const hue2rgb = (p, q, t) => {
      if (t < 0) { t += 1 }
      if (t > 1) { t -= 1 }
      if (t < 1 / 6) { return p + (q - p) * 6 * t }
      if (t < 1 / 2) { return q }
      if (t < 2 / 3) { return p + (q - p) * (2 / 3 - t) * 6 }
      return p
    }
    const q = l < 0.5 ? l * (1 + s) : l + s - l * s
    const p = 2 * l - q
    r = hue2rgb(p, q, h + 1 / 3)
    g = hue2rgb(p, q, h)
    b = hue2rgb(p, q, h - 1 / 3)
  }
  return {
    r: Math.round(r * 255),
    g: Math.round(g * 255),
    b: Math.round(b * 255),
    a: 1, // 默认不透明
  }
}

/**
 * RGB 混合
 */
function mixColors(color1, color2, weight) {
  const c1 = parseColor(color1)
  const c2 = parseColor(color2)
  if (!c1 || !c2) { return color1 }
  const r = Math.round(c1.r * (1 - weight) + c2.r * weight)
  const g = Math.round(c1.g * (1 - weight) + c2.g * weight)
  const b = Math.round(c1.b * (1 - weight) + c2.b * weight)
  const a = (c1.a * (1 - weight) + c2.a * weight).toFixed(2)
  return `rgba(${r}, ${g}, ${b}, ${a})`
}

/**
 * 设置 CSS 变量
 */
function applyColor(type, color, isDarkMode) {
  if (!color) {
    console.warn(`未获取到 ${type} 颜色的值`)
    return
  }

  const rgbColor = parseColor(color)
  if (rgbColor) {
    // 设置 --el-color-primary-rgb
    const rgbString = `${rgbColor.r}, ${rgbColor.g}, ${rgbColor.b}`
    html.style.setProperty(`--el-color-${type}-rgb`, rgbString)
  }

  const white = 'rgba(255, 255, 255,1)'
  const black = 'rgba(0, 0, 0)'
  const mixBase = isDarkMode ? black : white
  const base = `--el-color-${type}`
  html.style.setProperty(base, color)

  // 设置亮色层级变量
  Levels.forEach((level) => {
    html.style.setProperty(`${base}-light-${level}`, mixColors(color, mixBase, level * 0.1))
  })

  // 设置暗色层级变量
  const darkColor = mixColors(color, isDarkMode ? white : black, 0.2)
  html.style.setProperty(`${base}-dark-2`, darkColor)
}

/**
 * 主题 Hook
 */
export function useTheme(defaultTheme = {}, isDarkModeInitial = false) {
  const currentTheme = ref({ ...defaultTheme })
  const isDarkMode = ref(isDarkModeInitial) // 默认值控制初始是否为深色模式

  const setTheme = (theme) => {
    if (!theme || typeof theme !== 'object') {
      console.warn('主题配置应为对象')
      return
    }

    // 更新每个颜色类型
    for (const [type, color] of Object.entries(theme)) {
      applyColor(type, color, isDarkMode.value)
    }

    // 更新当前主题
    currentTheme.value = { ...theme }
  }

  const toggleDarkMode = (darkMode) => {
    isDarkMode.value = darkMode
    // 重新设置颜色，应用新的模式
    for (const [type, color] of Object.entries(currentTheme.value)) {
      applyColor(type, color, isDarkMode.value)
    }
  }

  // 初始化主题
  setTheme(defaultTheme)

  return {
    currentTheme,
    isDarkMode,
    setTheme,
    toggleDarkMode,
  }
}
